package com.dllo.lanou.cookapp.activity;

import android.content.Intent;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.android.volley.AuthFailureError;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.dllo.lanou.cookapp.R;
import com.dllo.lanou.cookapp.adapter.SearchCookListViewAdapter;
import com.dllo.lanou.cookapp.entity.BookList;
import com.dllo.lanou.cookapp.entity.HeadViewPageResultEntity;
import com.dllo.lanou.cookapp.entity.SearchFootEntity;
import com.dllo.lanou.cookapp.view.LoadListView;
import com.dllo.lanou.cookapp.volly.VolleySingleton;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;

public class SearchActivity extends AppCompatActivity implements View.OnClickListener,LoadListView.ILoadListener, AdapterView.OnItemClickListener {
@Bind(R.id.btnSearch)
    ImageView  btnSearch;
    @Bind(R.id.icon_back)
    ImageView icon_back;
    @Bind(R.id.etSearch)
    EditText etSearch;
    @Bind(R.id.ivDeleteText)
    ImageView ivDeleteText;

    @Bind(R.id.load_listview)
    LoadListView listview;

    @Bind(R.id.rlSearchFrameDelete)
    RelativeLayout rlSearchFrameDelete;

    @Bind(R.id.class_des_name)
    TextView class_des_name;
    private SearchCookListViewAdapter adapter;
    private    List<HeadViewPageResultEntity> list;


    private int page = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        ButterKnife.bind(this);

        Intent intent = getIntent();
        boolean  isClassity = intent.getBooleanExtra("classify",false);
        boolean isSearch = intent.getBooleanExtra("search",false);
        Log.i("bool", isClassity + "");
        if (isClassity == true){
            rlSearchFrameDelete.setVisibility(View.GONE);
            btnSearch.setVisibility(View.GONE);
            class_des_name.setVisibility(View.VISIBLE);
            class_des_name.setText(intent.getStringExtra("name"));
            long id = intent.getLongExtra("id",0);
            Log.i("bool",id+"");
            String classIdUrl = "http://www.tngou.net/api/cook/list?"+"id="+id;
            requestData(classIdUrl);
        }
        else if (isSearch == true){
            rlSearchFrameDelete.setVisibility(View.VISIBLE);
            btnSearch.setVisibility(View.VISIBLE);
            class_des_name.setVisibility(View.GONE);
            etSearch.addTextChangedListener(new TextWatcher() {

                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    // TODO Auto-generated method stub

                }

                public void beforeTextChanged(CharSequence s, int start, int count,
                                              int after) {
                    // TODO Auto-generated method stub

                }

                public void afterTextChanged(Editable s) {
                    if (s.length() == 0) {
                        ivDeleteText.setVisibility(View.GONE);
                    } else {
                        ivDeleteText.setVisibility(View.VISIBLE);
                    }
                }
            });


        }





        listview.setInterface(this);
        btnSearch.setOnClickListener(this);
        icon_back.setOnClickListener(this);
        ivDeleteText.setOnClickListener(this);
        list = new ArrayList<>();
        adapter = new SearchCookListViewAdapter(this);
        listview.setOnItemClickListener(this);
        listview.setAdapter(adapter);

    }




    @Override
    public void onClick(View v) {

        switch (v.getId()){
            case R.id.btnSearch://搜索
                String name = etSearch.getText().toString().trim();
                String path = "http://www.tngou.net/api/cook/name?"+"name="+name;
                requestData(path);
                break;
            case R.id.icon_back:
                finish();
                break;
            case R.id.ivDeleteText://删除
                etSearch.setText("");
                break;
        }

    }

    //请求数据
    public void requestData(String name) {

        StringRequest request = new StringRequest(name, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
               Log.i("bool的的数据", response);
                SearchFootEntity foodEntity = JSON.parseObject(response, SearchFootEntity.class);

                if (foodEntity != null){
                  list= foodEntity.getTngou();
                    Log.i("bool",list+"");
                   adapter.addData(list);

                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        }) {
            @Override
            //在StringRespset结束之前写{}在大括号里面写 getHeaders() 自动重写方法
            //用Map方法键值对形势添加
            //添加请求头
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put("apikey", "4ee0087cd4103e3acbab0f8efbf0bbd1");
                return map;
            }


        };
        VolleySingleton.getInstance().addRequest(request);
    }

    @Override
    public void onLoad() {
        //获取更多数据，
        // 通知UI更新
        //通知加载完毕
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                //获取更多数据，
                // 通知UI更新
                //通知加载完毕
                listview.loadComplete();
            }
        },2000);

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long ids) {

        HeadViewPageResultEntity entity =  list.get(position);
        long id = entity.getId();
        Intent intent = new Intent(this,DetatViewPagerActivity.class);
        intent.putExtra("id",id);
        startActivity(intent);
    }
}
